package cn.meebook.domain;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BookCircleRespository {

	@Autowired
	private BookRepository bookRepository;

	@Autowired
	private EntityManager entityManager;

	public List<DomainBookCircleNumber> listBookCircleNumber(List<BookDomain> books) {
		Long domain = books.get(0).getDomain().getId();
		String isbns = "(";
		Iterator<BookDomain> itBooks = books.iterator();
		while (itBooks.hasNext()) {
			isbns += "'" + itBooks.next().getBook().getIsbn() + "',";
		}
		isbns += "'')";
		
		List<DomainBookCircleNumber> dbcns = new ArrayList<>();
		Query query = entityManager	.createNativeQuery("SELECT * FROM DomainBookCircleNumber WHERE isbn IN " + isbns + " AND domain=" + domain);
		for (Object o : query.getResultList()) {
			Object[] tmp = (Object[]) o;
			DomainBookCircleNumber dbcn = new DomainBookCircleNumber((BigInteger) tmp[0], (Integer) tmp[1], (String) tmp[2], (BigInteger) tmp[3],
					(BigInteger) tmp[4]);
			dbcns.add(dbcn);
		}
		return dbcns;
	}

}
